const express = require("express");
const router = express.Router();
//引入cookie
// var cookieParser = require("cookie-parser");
// 引入数据库模块
var MongoClient = require("mongodb").MongoClient;
let objectId = require("mongodb").ObjectId;
let url = "mongodb://localhost:27017/userinfo";
// 封装连接数据库的方法
function getDb(callback) {
  MongoClient.connect(url, (err, db) => {
    callback(err, db);
  });
}
// 引入表单模块
var multiparty = require("multiparty");
// 引入fs文件处理模块
let fs = require("fs");
router.get("/ip", (req, res) => {
  fs.readFile("./router/ip.txt", "utf-8", (err, data) => {
    // console.log(err);
    //null 没有错误
    // console.log(data);
    //不存在自动创建文件
    if (err) {
      return res.json({ status: -1, info: "配置文件丢失！" });
    } else {
      return res.json({ status: 1, info: "配置文件获取成功！", data: data });
    }
  });
});
router.get("/config", (req, res) => {
  fs.readFile("./router/config.json", "utf-8", (err, data) => {
    // console.log(err);
    //null 没有错误
    // console.log(data);
    //不存在自动创建文件
    if (err) {
      return res.json({ status: -1, info: "配置文件丢失！" });
    } else {
      return res.json({
        status: 1,
        info: "配置文件获取成功！",
        data: JSON.parse(data),
      });
    }
  });
});

// 用户信息操作
//  用户信息添加路由
router.post("/adduser", (req, res) => {
  let form = new multiparty.Form();
  // 设置图片上传路径
  form.uploadDir = "static/upload";

  form.parse(req, (err, fields, files) => {
    if (fields.Mimg_0[0] != "") {
      var mfile_0 =
        "upload\\" +
        fields.Mimg_0[0].substr(fields.Mimg_0[0].lastIndexOf("/") + 1);
    }
    if (fields.Mimg_1[0] != "") {
      var mfile_1 =
        "upload\\" +
        fields.Mimg_1[0].substr(fields.Mimg_1[0].lastIndexOf("/") + 1);
    }
    if (fields.Mimg_2[0] != "") {
      var mfile_2 =
        "upload\\" +
        fields.Mimg_2[0].substr(fields.Mimg_2[0].lastIndexOf("/") + 1);
    }
    if (fields.Mimg_3[0] != "") {
      var mfile_3 =
        "upload\\" +
        fields.Mimg_3[0].substr(fields.Mimg_3[0].lastIndexOf("/") + 1);
    }
    if (fields.Mimg_4[0] != "") {
      var mfile_4 =
        "upload\\" +
        fields.Mimg_4[0].substr(fields.Mimg_4[0].lastIndexOf("/") + 1);
    }
    let username = fields.username[0];
    let call = fields.call[0];
    let address = fields.address[0];
    let buy = fields.buy[0];
    let newMoto = fields.newMoto[0];
    let sfz = fields.sfz[0];
    let sex = fields.sex[0];
    let birthday = fields.birthday[0];
    let date = fields.date[0]; //买保险
    let brand = fields.brand[0]; //车牌号
    let date1 = fields.date1[0]; //购车时间
    let date_sc = fields.date_sc[0]; //审车
    let date_jsz = fields.date_jsz[0]; //驾驶证
    let Moto = fields.Moto[0];
    let MotoType = fields.MotoType[0];
    let Money = fields.Money[0];
    let desc = fields.desc[0];
    let code = fields.code[0];
    let code_sc = fields.code_sc[0];
    let bx_true = fields.bx_true[0];
    let sc_true = fields.sc_true[0];
    let img = mfile_0;
    let img_xszfm = mfile_1;
    let img_qs = mfile_2;
    let img_new = mfile_3;
    let img_jsz = mfile_4;
    // 行驶证图片
    if (JSON.stringify(files) != "{}") {
      if (files.img != undefined) {
        img = files.img[0].path;
        img = img.substr(img.indexOf("\\") + 1);
      }
      if (files.img_qs != undefined) {
        //合格证图片
        img_qs = files.img_qs[0].path;
        img_qs = img_qs.substr(img_qs.indexOf("\\") + 1);
      }
      if (files.img_new != undefined) {
        // 新车合照
        img_new = files.img_new[0].path;
        img_new = img_new.substr(img_new.indexOf("\\") + 1);
      }
      if (files.img_jsz != undefined) {
        img_jsz = files.img_jsz[0].path;
        img_jsz = img_jsz.substr(img_jsz.indexOf("\\") + 1);
      }
      if (files.img_xszfm != undefined) {
        img_xszfm = files.img_xszfm[0].path;
        img_xszfm = img_xszfm.substr(img_xszfm.indexOf("\\") + 1);
      }
    }
    let insertData = {
      username,
      call,
      sfz,
      sex,
      birthday,
      address,
      brand,
      buy,
      newMoto,
      date,
      date1,
      date_sc,
      date_jsz,
      Moto,
      MotoType,
      Money,
      desc,
      img,
      img_xszfm,
      img_qs,
      img_new,
      img_jsz,
      code,
      code_sc,
      sc_true,
      bx_true,
    };
    getDb((err, db) => {
      db.collection("user").insertOne(insertData, (error, result) => {
        if (error) {
          return res.json({ status: -1, info: "添加失败" });
        } else {
          getDb((err, db) => {
            //点击添加  删除临时数据库
            db.collection("imgTemp").deleteMany({});
          });
          return res.json({ status: 1, info: "添加成功" });
        }
      });
    });
  });
});
// 用户信息更新
router.post("/update", (req, res) => {
  let _id = objectId(req.body._id);
  // console.log(_id)
  let username = req.body.username;
  let call = req.body.call;
  let address = req.body.address;
  let buy = req.body.buy;
  let newMoto = req.body.newMoto;
  let brand = req.body.brand;
  let sfz = req.body.sfz;
  let sex = req.body.sex;
  let birthday = req.body.birthday;
  if (sfz == "") {
    sex = "";
    birthday = "";
  }
  let date = req.body.date;
  let date1 = req.body.date1;
  let date_sc = req.body.date_sc;
  let Moto = req.body.Moto;
  let MotoType = req.body.MotoType;
  let Money = req.body.Money;
  let desc = req.body.desc;
  let towns = req.body.towns;
  let code = req.body.code;
  let code_sc = req.body.code_sc;
  let sc_true = req.body.sc_true;
  let bx_true = req.body.bx_true;

  let updateData = {
    $set: {
      username,
      call,
      address,
      buy,
      newMoto,
      sfz,
      sex,
      brand,
      birthday,
      date,
      date1,
      date_sc,
      Moto,
      MotoType,
      Money,
      desc,
      towns,
      code,
      code_sc,
      bx_true,
      sc_true,
    },
  };
  getDb((err, db) => {
    db.collection("user").updateOne({ _id }, updateData, (error, result) => {
      if (error) {
        return res.json({ status: -1, info: "修改失败" });
      } else {
        return res.json({ status: 1, info: "修改成功" });
      }
    });
  });
});

router.get("/clearDb", (req, res) => {
  getDb((err, db) => {
    //清除数据库
    db.collection("imgTemp").deleteMany({});
  });
  return res.json({ state: 1, info: "入口数据清除成功！" });
});
//2021-12-5 test
// 手机照片
router.post("/ed", (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = "static/upload";
  form.parse(req, (err, fields, files) => {
    if (req.body.clear) {
      getDb((err, db) => {
        db.collection("imgTemp")
          .find()
          .toArray((error, result) => {
            // console.log(result);
            // 入口删除本图片
            if (result.length > 0) {
              result.forEach((e, i) => {
                fs.unlink("./" + e.imgUrl, (err) => {});
              });
            }
            // 清除数据库
            getDb((err, db) => {
              //清除数据库
              db.collection("imgTemp").deleteMany({});
            });
            return res.json({ state: 1, info: "入口数据清除成功！" });
          });
      });
    }

    let temp = undefined;
    if (fields) {
      // var Time;
      // a[0]== 1上传图片   a[0]==2 读取图片
      if (fields.a[0] == 1 && Object.keys(files).length > 0) {
        getDb((err, db) => {
          temp = files.url[0].path;
          db.collection("imgTemp")
            .find()
            .toArray((error, result) => {
              if (result.length <= 0) {
                getDb((err, db) => {
                  db.collection("imgTemp").insertOne(
                    { imgUrl: temp, imgName: fields.imgName[0] },
                    (error, result) => {
                      if (error) {
                        return res.json({
                          status: -1,
                          info: "临时文件添加失败",
                        });
                      } else {
                        return res.json({
                          status: 1,
                          info: "临时文件添加成功",
                        });
                      }
                    }
                  );
                });
              } else {
                let a = 1;
                result.forEach((e, i) => {
                  let imgNameTmp = e.imgName;
                  if (e.imgName == fields.imgName[0]) {
                    getDb((err, db) => {
                      fs.unlink("./" + e.imgUrl, (err) => {});
                      db.collection("imgTemp").deleteOne(
                        { imgName: imgNameTmp },
                        (error, result) => {}
                      );
                    });
                    getDb((err, db) => {
                      if (a == 1) {
                        a--;
                        db.collection("imgTemp").insertOne(
                          { imgUrl: temp, imgName: fields.imgName[0] },
                          (error, result) => {
                            if (error) {
                              return res.json({
                                status: -1,
                                info: "临时文件添加失败",
                              });
                            } else {
                              return res.json({
                                status: 1,
                                info: "临时文件添加成功",
                              });
                            }
                          }
                        );
                      }
                    });
                  } else {
                    if (a == 1) {
                      a--;
                      getDb((err, db) => {
                        db.collection("imgTemp").insertOne(
                          { imgUrl: temp, imgName: fields.imgName[0] },
                          (error, result) => {
                            if (error) {
                              return res.json({
                                status: -1,
                                info: "临时文件添加失败",
                              });
                            } else {
                              return res.json({
                                status: 1,
                                info: "临时文件添加成功",
                              });
                            }
                          }
                        );
                      });
                    }
                  }
                });
              }
            });
        });
      } else if (fields.a[0] == 2) {
        getDb((err, db) => {
          db.collection("imgTemp")
            .find()
            .toArray((error, result) => {
              //点击上传成功  移动图片 然后删除本图片
              return res.json({ status: 1, info: "获取成功", data: result });
            });
        });
      }
    }
  });
});
// 修改行驶证图片(pc版本)
router.post("/editimg", (req, res) => {
  // console.log(req.body)
  let form = new multiparty.Form();
  // 设置图片上传路径
  form.uploadDir = "static/upload";
  form.parse(req, (err, fields, files) => {
    // console.log(fields.imgName[0]);
    var tmpImgName = fields.imgName[0]; //标记修改的字段名
    let oldimg = fields.oldimg[0].slice(-35); //旧图地址
    // console.log(oldimg);
    // console.log(fields.oldimg[0]);
    // return 0;
    fs.unlink("./" + oldimg, (err) => {}); //删除旧图
    fs.unlink("./static/" + oldimg, (err) => {}); //删除旧图
    let imgPath = {};
    // console.log(files);
    // console.log(fields);
    // return 0;
    let imgTemp;

    if (JSON.stringify(files) == "{}") {
      imgTemp = fields[tmpImgName][0];
    } else {
      imgTemp = files[tmpImgName][0].path;
    }
    // img 图片路径    tmpImgName  索引名
    // console.log(imgTemp + "----390");
    // return 0;
    imgTemp = imgTemp.substr(imgTemp.indexOf("\\") + 1);
    if (tmpImgName == "img") {
      let img = imgTemp;
      imgPath = { img };
    } else if (tmpImgName == "img_xszfm") {
      let img_xszfm = imgTemp;
      imgPath = { img_xszfm };
    } else if (tmpImgName == "img_qs") {
      let img_qs = imgTemp;
      imgPath = { img_qs };
    } else if (tmpImgName == "img_new") {
      let img_new = imgTemp;
      imgPath = { img_new };
    } else if (tmpImgName == "img_jsz") {
      let img_jsz = imgTemp;
      imgPath = { img_jsz };
    }
    let _id = objectId(fields._id[0]);
    getDb((err, db) => {
      db.collection("user").updateOne(
        { _id },
        { $set: imgPath },
        (error, result) => {
          if (error) {
            return res.json({ status: -1, info: "修改失败" });
          } else {
            return res.json({ status: 1, info: "修改成功" });
          }
        }
      );
    });
  });
});
//  用户信息查找路由
router.post("/finduser", (req, res) => {
  // console.log(req.body)
  if (req.body.id == "LXuao") {
    getDb((err, db) => {
      db.collection("user")
        .find()
        .toArray((error, result) => {
          return res.json({ status: 1, info: "获取成功", data: result });
        });
    });
  }
});
//  单个用户信息查找路由
router.post("/findone", (req, res) => {
  // console.log(req.body)
  let _id = objectId(req.body.id);
  getDb((err, db) => {
    db.collection("user")
      .find({ _id })
      .toArray((error, result) => {
        return res.json({ status: 1, info: "获取成功", data: result });
      });
  });
});
// 删除用户信息
router.post("/deluser", (req, res) => {
  // 获取基本参数(id)
  // console.log(req.body)
  let _id = objectId(req.body.id);
  fs.unlink("./" + req.body.imgurl, (err) => {});
  fs.unlink("./static/" + req.body.imgurl, (err) => {});
  fs.unlink("./" + req.body.img_fm, (err) => {});
  fs.unlink("./static/" + req.body.img_fm, (err) => {});
  fs.unlink("./" + req.body.img_qs, (err) => {});
  fs.unlink("./static/" + req.body.img_qs, (err) => {});
  fs.unlink("./" + req.body.img_new, (err) => {});
  fs.unlink("./static/" + req.body.img_new, (err) => {});
  fs.unlink("./" + req.body.img_jsz, (err) => {});
  fs.unlink("./static/" + req.body.img_jsz, (err) => {});

  // 执行删除操作
  getDb((err, db) => {
    db.collection("user").deleteOne({ _id }, (error, result) => {
      if (error) {
        return res.json({ status: -1, info: "删除失败" });
      } else {
        return res.json({ status: 1, info: "删除成功" });
      }
    });
  });
});
// 模糊查询信息
router.post("/finduserinfo", (req, res) => {
  let reg = new RegExp(req.body.info);
  getDb((err, db) => {
    db.collection("user")
      .find({
        $or: [
          { username: reg },
          { towns: reg },
          { address: reg },
          { call: reg },
          { MotoType: reg },
          { date1: reg },
        ],
      })
      .toArray((error, result) => {
        if (error) {
          return res.json({ status: -1, info: "查找失败" });
        } else {
          return res.json({ status: 1, info: "查找成功", data: result });
        }
      });
  });
});
// 查询买保险当月的用户详细信息
router.post("/findbx", (req, res) => {
  // console.log(req.body)
  let code = req.body.date;
  getDb((err, db) => {
    db.collection("user")
      .find({ code })
      .toArray((error, result) => {
        return res.json({ status: 1, info: "获取成功", data: result });
      });
  });
});
// 清除购保险信息
setInterval(() => {
  let date = new Date();
  if (
    date.getMonth() + 1 == 12 &&
    date.getDate() == 31 &&
    date.getHours() == 23
  ) {
    getDb((err, db) => {
      db.collection("user")
        .find({ bx_true: true }, { bx_true: true })
        .forEach((item) => {
          db.collection("user").update(
            { bx_true: true },
            { $set: { bx_true: false } }
          );
        });
      db.collection("user")
        .find({ sc_true: true }, { sc_true: true })
        .forEach((item) => {
          db.collection("user").update(
            { sc_true: true },
            { $set: { sc_true: false } }
          );
        });
    });
  }
}, 1800000);
router.get("/clearbx", (req, res) => {
  getDb((err, db) => {
    db.collection("user")
      .find({ bx_true: true }, { bx_true: true })
      .forEach((item) => {
        db.collection("user").update(
          { bx_true: true },
          { $set: { bx_true: false } }
        );
      });
  });
});
// 清除审车信息
router.get("/clearsc", (req, res) => {
  getDb((err, db) => {
    db.collection("user")
      .find({ sc_true: true }, { sc_true: true })
      .forEach((item) => {
        db.collection("user").update(
          { sc_true: true },
          { $set: { sc_true: false } }
        );
      });
  });
});
// 导出路由
module.exports = router;
/** 更新日志
 * V3.4.1
 * 2021-3-7   新增跨年修改买保险和审车为false
 *            新增添加行驶证反面图片
 * 2021-3-8   移除修改购保true为独立文件
 *            ip地址独立文件，后期直接修改log文件
 *            当年审车设置为橙色，需要骑车的设置为红色
 * 2021-3-15  新增登陆验证，取消首次购保，首次审车提示
 *            审车提示修改为首次审车
 * 更新测试
 * 2021-3-26 v3.5.8
 *            新增修改图片后不影响已填信息
 * 2021-3-30 v3.5.9
 *            驾驶证高亮提示
 * 2021-4-13 独家更新
 *             短信发送
 * v3.6.1
 * 2021-6-28
 *          更新清除保险 审车操作
 * v3.6.3
 * 2021-7-26
 *         修复审车时间bug
 * v3.6.6
 * 2021-11-11
 *         删除短信发送
 *         更新保存当前进入页数，点击返回后返回当前页数
 *         保存月份查询记录，点击返回后展示当前查询的页数
 * V3.6.8
 * 2021-11-13
 *        优化部分逻辑代码
 * V3.7.0
 * 2021-11-14
 *        新增模拟选牌功能
 * V3.8.15
 * 2021-11-26
 *      修复bug01
 *      新增销量统计功能
 * V3.9.10
 * 2021-12-5
 *      新增手机照片同步到电脑
 *      新增用户信息添加时可选择是否审车
 * V3.9.12
 * 2021-12-8
 *      页面跳转后&搜索框输入后清除cookie
 *      布局
 * V3.9.13
 * 2021-12-10
 *     修复图片删除问题
 * V3.9.21
 * 2021-12-18
 *     优化时间排序
 *     删除手机照片提示
 *     更新自动清除购保险，审车时间
 * v3.9.23
 * 2021-12-21
 *     修复点击页面后再点击审车为空
 *     三个搜索框不冲突
 * V3.9.24
 * 2022-1-1
 *     修复同年审车无提示
 * V3.10.2
 * 2022-1-7
 *     新增统计图表
 * */
